﻿using System;
using System.Windows.Forms;
using System.Linq;
using System.Data;
using System.Data.SqlClient;

namespace liwuyou.sprider
{
    partial class frmSetDB : Form
    {
        SqlConnection con;
        SysCfgDataContext syscontext = new SysCfgDataContext();

        public frmSetDB()
        {
            InitializeComponent();
        }

        // 取消保存设置
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 读取数据库
        private void readDatabaseConfig()
        {
            var query = common.ReadConfigDBToQuery();

            foreach (SysConfig item in query)
            {
                switch (item.Code)
                {
                    case "db_host":
                        this.tbHost.Text = item.Value.Trim();
                        break;

                    case "db_name":
                        this.tbdbname.Text = item.Value.Trim();
                        break;

                    case "db_username":
                        this.tbUserName.Text = item.Value.Trim();
                        break;

                    case "db_pwd":
                        this.tbPwd.Text = item.Value.Trim();
                        break;
                }
            }
        }
        #endregion

        private void frmSetDB_Load(object sender, EventArgs e)
        { 
            this.readDatabaseConfig();
        }

        private void frmSetDB_Activated(object sender, EventArgs e)
        {
            tbHost.Focus();
        }

        /// <summary>
        /// 验证输入框的输入内容
        /// </summary>
        /// <param name="textbox">输入框控件</param>
        /// <param name="length">最大输入长度</param>
        /// <param name="controlName">输入框的名称</param>
        /// <returns>true验证通过，false验证不通过</returns>
        private bool validaing(TextBox textbox, int length, string controlName)
        {
            bool result = false;
            if (textbox.TextLength == 0)
            {
                this.errorProviderDB.SetError(textbox, "请输入" + controlName);
                textbox.SelectAll();
                textbox.Focus();

            }
            else if (textbox.TextLength > length)
            {
                this.errorProviderDB.SetError(textbox, "请输入小于" + length.ToString() + "个字符的" + controlName + "！");
                textbox.SelectAll();
                textbox.Focus();
            }
            else
            {
                this.errorProviderDB.SetError(textbox, "");
                result = true;
            }
            return result;

        }

        /// <summary>
        /// 保存数据库设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            // 验证数据库设置填写
            if (validaing(tbHost, 20, "数据库地址") == false)
            { return; }
            if (validaing(tbdbname, 50, "数据库名称") == false)
            { return; }
            if (validaing(tbUserName, 20, "数据库用户名") == false)
            { return; }
            if (validaing(tbPwd, 50, "数据库密码") == false)
            { return; }

            // 写入数据库
            var query = from cfg in syscontext.SysConfigs
                        where cfg.Group == "db"
                        select cfg;
            foreach (SysConfig item in query)
            {
                switch (item.Code)
                {
                    case "db_host":
                        item.Value = this.tbHost.Text.Trim();
                        break;

                    case "db_name":
                        item.Value = this.tbdbname.Text.Trim();
                        break;

                    case "db_username":
                        item.Value = this.tbUserName.Text.Trim();
                        break;

                    case "db_pwd":
                        item.Value = this.tbPwd.Text.Trim();
                        break;
                    default:
                        item.Value = item.Value;
                        break;
                }           
            }

            try
            {
                syscontext.SubmitChanges();

                MessageBox.Show("修改成功", "提示");

                this.Close();
            }
            catch
            {
                MessageBox.Show(e.ToString(), "错误");
            }
        }

        #region 禁止和允许按钮
        private void DisableButton()
        {
            progressBar1.Visible = true;
            this.btnSave.Enabled = false;
            this.btnCancel.Enabled = false;
            this.btnTestConnetc.Enabled = false;
        }

        private void EnableButton()
        {
            progressBar1.Visible = false;
            this.btnSave.Enabled = true;
            this.btnCancel.Enabled = true;
            this.btnTestConnetc.Enabled = true;
        }
        #endregion

        #region 后台连接数据库测试
        /// <summary>
        /// 用户按下测试连接按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestConnetc_Click(object sender, EventArgs e)
        {
            //先测试主机是否连通
            if (!Connect.NetPortOp.ConnValidate(tbHost.Text.Trim(), 1433, 1000))
            {
                MessageBox.Show(tbHost.Text.Trim()+"主机无法连通，请检查IP地址是否正确！", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //开始后台操作
            this.backgroundWorker1.RunWorkerAsync();
            //按钮失效
            DisableButton();
            //等待完成
            while (this.backgroundWorker1.IsBusy)
            {
                Application.DoEvents();
            }
            //完成
            //恢复按钮
            EnableButton();
        }

        /// <summary>
        /// 后台连接数据库中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string gs_ConnectionString = "Server=" + tbHost.Text.Trim() + ";Persist Security Info=True;uid=" + tbUserName.Text.Trim() +
                                        ";password=" + tbPwd.Text.Trim() + ";Initial Catalog=" + tbdbname.Text.Trim() + ";Connect Timeout=20";
            try
            {
                con = new SqlConnection(gs_ConnectionString);
                con.Open();
            }
            catch (Exception) { }
        }

        /// <summary>
        /// 后台连接数据库完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
                MessageBox.Show("数据库联机成功！", "数据库验证成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("数据库联机失败，请检查数据库名称、用户名、密码是否正确！", "数据库验证错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        #endregion

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
